package com.example.exam.servlet;

import com.example.exam.dao.StudentDAO;
import com.example.exam.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 个人信息Servlet
 */
@WebServlet("/profile")
public class ProfileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private StudentDAO studentDAO = new StudentDAO();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        // 获取学生信息
        Student student = (Student) session.getAttribute("student");
        
        // 转发到个人信息页面
        request.setAttribute("student", student);
        request.getRequestDispatcher("/WEB-INF/views/profile.html").forward(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        // 获取当前学生信息
        Student currentStudent = (Student) session.getAttribute("student");
        
        // 获取表单参数
        String major = request.getParameter("major");
        String grade = request.getParameter("grade");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");
        
        // 更新学生信息
        currentStudent.setMajor(major);
        currentStudent.setGrade(grade);
        currentStudent.setPhone(phone);
        currentStudent.setEmail(email);
        currentStudent.setAddress(address);
        
        // 更新数据库
        if (studentDAO.updateStudentInfo(currentStudent)) {
            request.setAttribute("message", "个人信息更新成功");
        } else {
            request.setAttribute("error", "个人信息更新失败");
        }
        
        // 转发到个人信息页面
        request.setAttribute("student", currentStudent);
        request.getRequestDispatcher("/WEB-INF/views/profile.html").forward(request, response);
    }
}    